package com.zuimei.zuimei.adapters;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zuimei.zuimei.R;

import org.wlf.filedownloader.DownloadFileInfo;
import org.wlf.filedownloader.FileDownloader;
import org.wlf.filedownloader.base.Status;
import org.wlf.filedownloader.listener.OnFileDownloadStatusListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Jogger on 2017/1/26.
 * 下载列表适配器
 */

public class DownloadFileListAdapter extends RecyclerView.Adapter<DownloadFileListAdapter
        .MyViewHolder> implements OnFileDownloadStatusListener {

    /**
     * LOG TAG
     */
    private static final String TAG = DownloadFileListAdapter.class.getSimpleName();

    // all download infos
    private List<DownloadFileInfo> mDownloadFileInfos = Collections.synchronizedList(new
            ArrayList<DownloadFileInfo>());
    // cached convert views
    private Map<String, View> mConvertViews = new LinkedHashMap<String, View>();
    // select download file infos
    private List<DownloadFileInfo> mSelectedDownloadFileInfos = new ArrayList<DownloadFileInfo>();

    private Context mContext;

    private OnItemSelectListener mOnItemSelectListener;

    public DownloadFileListAdapter(Context context) {
        super();
        mContext = context;
        initDownloadFileInfos();
    }

    // 初始化 DownloadFileInfos
    private void initDownloadFileInfos() {
        this.mDownloadFileInfos = FileDownloader.getDownloadFiles();
        mConvertViews.clear();
        mSelectedDownloadFileInfos.clear();
        if (mOnItemSelectListener != null) {
            mOnItemSelectListener.onNoneSelect();
        }
    }

    /**
     * update show
     */
    public void updateShow() {
        initDownloadFileInfos();
        notifyDataSetChanged();
    }

    public void setOnItemSelectListener(OnItemSelectListener onItemSelectListener) {
        this.mOnItemSelectListener = onItemSelectListener;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.rv_download_item, parent,
                false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        DownloadFileInfo downloadFileInfo = mDownloadFileInfos.get(position);
        final String url = downloadFileInfo.getUrl();
        holder.tv_title.setText(downloadFileInfo.getFileName());
        // download progress
        int totalSize = (int) downloadFileInfo.getFileSizeLong();
        int downloaded = (int) downloadFileInfo.getDownloadedSizeLong();
        double rate = (double) totalSize / Integer.MAX_VALUE;
        if (rate > 1.0) {
            totalSize = Integer.MAX_VALUE;
            downloaded = (int) (downloaded / rate);
        }
        holder.pb_download.setMax(totalSize);
        holder.pb_download.setProgress(downloaded);
        // file size
        double downloadSize = downloadFileInfo.getDownloadedSizeLong() / 1024f / 1024;
        double fileSize = downloadFileInfo.getFileSizeLong() / 1024f / 1024;

        //holder.tv_file_size.setText(((float) (Math.round(downloadSize * 100)) / 100) + "M/");
        holder.tv_file_size.setText(((float) (Math.round(fileSize * 100)) / 100) + "M");

        // downloaded percent
        //double percent = downloadSize / fileSize * 100;
        //tvPercent.setText(((float) (Math.round(percent * 100)) / 100) + "%");
        switch (downloadFileInfo.getStatus()) {
            // download file status:unknown
            case Status.DOWNLOAD_STATUS_UNKNOWN:
                break;
            // download file status:retrying
            case Status.DOWNLOAD_STATUS_RETRYING:
                break;
            // download file status:preparing
            case Status.DOWNLOAD_STATUS_PREPARING:
                break;
            // download file status:prepared
            case Status.DOWNLOAD_STATUS_PREPARED:
                break;
            // download file status:paused
            case Status.DOWNLOAD_STATUS_PAUSED:
                break;
            // download file status:downloading
            case Status.DOWNLOAD_STATUS_DOWNLOADING:
                break;
            // download file status:error
            case Status.DOWNLOAD_STATUS_ERROR:
                break;
            // download file status:waiting
            case Status.DOWNLOAD_STATUS_WAITING:
                break;
            // download file status:completed
            case Status.DOWNLOAD_STATUS_COMPLETED:
                holder.tv_file_size.setText("");
                break;
            // download file status:file not exist
            case Status.DOWNLOAD_STATUS_FILE_NOT_EXIST:
                holder.tv_file_size.setText("");
                break;
        }

        holder.cb_select.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mSelectedDownloadFileInfos.add(FileDownloader.getDownloadFile(url));
                    if (mOnItemSelectListener != null) {
                        // select a download file
                        mOnItemSelectListener.onSelected(mSelectedDownloadFileInfos);
                    }
                } else {
                    mSelectedDownloadFileInfos.remove(FileDownloader.getDownloadFile(url));
                    if (mSelectedDownloadFileInfos.isEmpty()) {
                        if (mOnItemSelectListener != null) {
                            // select none
                            mOnItemSelectListener.onNoneSelect();
                        }
                    } else {
                        if (mOnItemSelectListener != null) {
                            // select a download file
                            mOnItemSelectListener.onSelected(mSelectedDownloadFileInfos);
                        }
                    }
                }
            }
        });

        setBackgroundOnClickListener(holder.ll_item_container, downloadFileInfo);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return mDownloadFileInfos.size();
    }

    // set convertView click
    private void setBackgroundOnClickListener(final View lnlyDownloadItem, final DownloadFileInfo
            curDownloadFileInfo) {

        lnlyDownloadItem.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                final Context context = v.getContext();
                if (curDownloadFileInfo != null) {
                    switch (curDownloadFileInfo.getStatus()) {
                        // download file status:unknown
                        case Status.DOWNLOAD_STATUS_UNKNOWN:
                            break;
                        // download file status:error & paused
                        case Status.DOWNLOAD_STATUS_ERROR:
                        case Status.DOWNLOAD_STATUS_PAUSED:
                            FileDownloader.start(curDownloadFileInfo.getUrl());
                            break;
                        // download file status:file not exist
                        case Status.DOWNLOAD_STATUS_FILE_NOT_EXIST:
                            // show dialog
                            break;
                        // download file status:retrying & waiting & preparing & prepared &
                        // downloading
                        case Status.DOWNLOAD_STATUS_RETRYING:
                        case Status.DOWNLOAD_STATUS_WAITING:
                        case Status.DOWNLOAD_STATUS_PREPARING:
                        case Status.DOWNLOAD_STATUS_PREPARED:
                        case Status.DOWNLOAD_STATUS_DOWNLOADING:
                            // pause
                            FileDownloader.pause(curDownloadFileInfo.getUrl());
                            break;
                        // download file status:completed
                        case Status.DOWNLOAD_STATUS_COMPLETED:

                            TextView tvDownloadSize = (TextView) lnlyDownloadItem.findViewById(R
                                    .id.tv_file_size);
                            if (tvDownloadSize != null) {
                                tvDownloadSize.setText("");
                            }
                            break;
                    }
                }
            }
        });
    }

    /**
     * add new download file info
     */
    public boolean addNewDownloadFileInfo(DownloadFileInfo downloadFileInfo) {
        if (downloadFileInfo != null) {
            if (!mDownloadFileInfos.contains(downloadFileInfo)) {
                boolean isFind = false;
                for (DownloadFileInfo info : mDownloadFileInfos) {
                    if (info != null && info.getUrl().equals(downloadFileInfo.getUrl())) {
                        isFind = true;
                        break;
                    }
                }
                if (isFind) {
                    return false;
                }
                mDownloadFileInfos.add(downloadFileInfo);
                notifyDataSetChanged();
                return true;
            }
        }
        return false;
    }

    // ///////////////////////////////////////////////////////////

    // ----------------------download status callback----------------------
    @Override
    public void onFileDownloadStatusWaiting(DownloadFileInfo downloadFileInfo) {

        if (downloadFileInfo == null) {
            return;
        }

        // add
        if (addNewDownloadFileInfo(downloadFileInfo)) {
            // add succeed
            notifyDataSetChanged();
        } else {
            updateShow();
        }
    }

    @Override
    public void onFileDownloadStatusPreparing(DownloadFileInfo downloadFileInfo) {

        if (downloadFileInfo == null) {
            return;
        }
        updateShow();
    }

    @Override
    public void onFileDownloadStatusPrepared(DownloadFileInfo downloadFileInfo) {

        if (downloadFileInfo == null) {
            return;
        }
        updateShow();
    }

    @Override
    public void onFileDownloadStatusDownloading(DownloadFileInfo downloadFileInfo, float
            downloadSpeed, long
                                                        remainingTime) {

        if (downloadFileInfo == null) {
            return;
        }
        // download progress
        int totalSize = (int) downloadFileInfo.getFileSizeLong();
        int downloaded = (int) downloadFileInfo.getDownloadedSizeLong();
        double rate = (double) totalSize / Integer.MAX_VALUE;
        if (rate > 1.0) {
            totalSize = Integer.MAX_VALUE;
            downloaded = (int) (downloaded / rate);
        }
        // pbProgress.setMax(totalSize);
        //pbProgress.setProgress(downloaded);

        // download size
        double downloadSize = downloadFileInfo.getDownloadedSizeLong() / 1024f / 1024f;
        double fileSize = downloadFileInfo.getFileSizeLong() / 1024f / 1024f;

        //tvDownloadSize.setText(((float) (Math.round(downloadSize * 100)) / 100) + "M/");
        //tvTotalSize.setText(((float) (Math.round(fileSize * 100)) / 100) + "M");

        // download speed and remain times
        //setBackgroundOnClickListener(lnlyDownloadItem, downloadFileInfo);
        updateShow();

    }

    @Override
    public void onFileDownloadStatusPaused(DownloadFileInfo downloadFileInfo) {

        if (downloadFileInfo == null) {
            return;
        }

    }

    @Override
    public void onFileDownloadStatusCompleted(DownloadFileInfo downloadFileInfo) {

        if (downloadFileInfo == null) {
            return;
        }

        Log.d(TAG, "----下载完成");
    }

    @Override
    public void onFileDownloadStatusFailed(String url, DownloadFileInfo downloadFileInfo,
                                           FileDownloadStatusFailReason failReason) {

        if (downloadFileInfo == null) {
            return;
        }
//
//        url = downloadFileInfo.getUrl();
//        View cacheConvertView = mConvertViews.get(url);
//        if (cacheConvertView != null) {
//
//            LinearLayout lnlyDownloadItem = (LinearLayout) cacheConvertView.findViewById(R.id
//                    .lnlyDownloadItem);
//            TextView tvText = (TextView) cacheConvertView.findViewById(R.id.tvText);
//
//            tvText.setText(msg);
//            showToast(msg + "，url：" + url);
//
//            setBackgroundOnClickListener(lnlyDownloadItem, downloadFileInfo);
//
//            Log.d(TAG, "onFileDownloadStatusFailed 出错回调，url：" + url + "，status(正常应该是" + Status
//                    .DOWNLOAD_STATUS_ERROR
//                    + ")：" + downloadFileInfo.getStatus());
//        } else {
//            updateShow();
//        }
    }

    /**
     * OnItemSelectListener
     */
    public interface OnItemSelectListener {

        void onSelected(List<DownloadFileInfo> selectDownloadFileInfos);

        void onNoneSelect();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        private CheckBox cb_select;
        private RelativeLayout rl_load_container;
        private ImageView iv_icon;
        private TextView tv_title;
        private ProgressBar pb_download;
        private TextView tv_pause;
        private TextView tv_file_size;
        private LinearLayout ll_item_container;

        public MyViewHolder(View itemView) {
            super(itemView);
            cb_select = (CheckBox) itemView.findViewById(R.id.cb_select);
            rl_load_container = (RelativeLayout) itemView.findViewById(R.id.rl_load_container);
            iv_icon = (ImageView) itemView.findViewById(R.id.iv_icon);
            tv_title = (TextView) itemView.findViewById(R.id.tv_title);
            pb_download = (ProgressBar) itemView.findViewById(R.id.pb_download);
            tv_pause = (TextView) itemView.findViewById(R.id.tv_pause);
            tv_file_size = (TextView) itemView.findViewById(R.id.tv_file_size);
            ll_item_container = (LinearLayout) itemView.findViewById(R.id.ll_item_container);
        }
    }
}